import store from '@/store'

export const request = (options) => {
	if (options.loading) {
		uni.showLoading({
			title: '加载中'
		})
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url,
			data: options.data || {},
			method: options.method || 'GET',
			header: {
				'content-type': 'application/json',
				'Authorization': getToken()
			},
			success: (res) => {
				if (options.loading) {
					uni.hideLoading()
				}

				if (!res || !res.data || !res.data.code) {

				} else if (res.data.code == 200) {
					return resolve(res.data)
				} else if (res.data.code == 401) {
					if (!store.state.isLoginPage) {
						store.state.isLoginPage = true
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
					return
				} else if (res.data.msg) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					})
					return
				}
			},
			fail: (err) => {
				if (options.loading) {
					uni.hideLoading()
				}

				reject(err)
			}
		})
	})
}

function getToken() {
	let cache = uni.getStorageSync('accessToken')

	// let cache = Store.state.userToken
	// if (!cache) {
	// 	cache = uni.getStorageSync('yunbang_user_token')
	// 	if (cache) {
	// 		Store.commit('setUserToken', cache)
	// 	} else {
	// 		cache = ''
	// 	}
	// }

	return cache
}
